<?php
/**
 * Created by PhpStorm.
 * User: 国小果
 * Date: 2022/11/29
 * Time: 18:03
 */

namespace app\backmanage\controller;

use app\common\model\common\Config as Model;
use thans\layuiAdmin\facade\AdminsAuth;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\facade\Utils;
use thans\layuiAdmin\Form;
use thans\layuiAdmin\Traits\FormActions;
use think\Request;
use think\facade\View;
use app\common\lib\BaseSqlConfig;

class Config extends Base
{
    use FormActions;
    protected $route_alias = 'config';
    protected $title       = '配置管理';

    public function index(Request $request)
    {
        if ($request->isAjax() || $request->isPost()) {
            list($where, $order, $page, $limit) = Utils::buildParams('id|name|value|group|desc|data_type|create_time|update_time');
            $model   = new Model();
            $where[] = ['status', '=', 1];
            $list    = $model->where($where)->page($page, $limit)->order($order)->field('id,name,value,group,desc,data_type,create_time,update_time')->select();
            $count   = $model->where($where)->count();
            Json::success('获取成功', $list, ['total' => $count, 'count' => $count]);
        } else {
            $data             = [];
            $data['cols']     = [
                ['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => 80],
                ['field' => 'name', 'title' => '变量名称', 'width' => 250],
                ['field' => 'value', 'title' => '变量值', 'width' => 350],
                ['field' => 'group', 'title' => '分组名', 'width' => 250],
                ['field' => 'desc', 'title' => '描述', 'width' => 250],
                ['field' => 'data_type', 'title' => '字段类型', 'type' => "button", 'option' => [[1, 'string',], [2, 'int'], [3, 'json'], [4, 'bool'], [5, 'float'], [6, 'array']], 'width' => 100],
                ['field' => 'create_time', 'title' => '创建时间', 'width' => 200],
                ['field' => 'update_time', 'title' => '修改时间', 'width' => 200],
                ['field' => 'right', 'title' => '操作', 'toolbar' => '#barDemo', 'width' => 150],
            ];
            $data['title']    = $this->title;
            $data['search'][] = ['type' => 'text', 'field' => 'keyword', 'desc' => '请输入标题关键字'];

            //url init
            $data['list_url'] = '/backmanage/' . $this->route_alias . '/index';
            $create_url       = $edit_url = '/backmanage/' . $this->route_alias . '/edit';
            $del_url          = '/backmanage/' . $this->route_alias . '/update';
            if (AdminsAuth::check($create_url)) {
                $data['create_url'] = $create_url;
            }
            if (AdminsAuth::check($edit_url)) {
                $data['edit_url'] = $edit_url;
            }
            if (AdminsAuth::check($del_url)) {
                $data['del_url'] = $del_url;
            }
            //$data['is_sync']=1;
            return View::fetch('', $data);
        }
    }

    public function check_admin(Request $request)
    {
        $pwd = env('ADMIN_PWD');
        $res = $pwd == $request->param('code') ? true : false;
        return json(['code' => $res]);
    }

    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $model = empty($request->param('id')) ? new Model() : Model::find($request->param('id'));

            $model->name        = $request->param('name');
            $model->group       = $request->param('group');
            $model->desc        = $request->param('desc');
            $model->value       = $request->param('value');
            $model->data_type   = $request->param('data_type');
            $model->update_time = time();
            $model->save();

            return json(['code' => 0, 'msg' => '修改成功', 'data' => '']);
        } else {
            $data = empty($request->param('id')) ? [] : Model::find($request->param('id'))->toArray();
            return View::fetch('config/edit', $data + ['title' => $this->title]);
        }
    }

    private function buildForm()
    {
        $model = new Model();
        $form  = new Form($model, []);

        $form->text()->name('name')->label('变量名称')->placeholder('变量名称')->rules('required');
        $form->text()->name('value')->label('变量值')->placeholder('变量值')->rules('required');
        $form->text()->name('group')->label('分组名')->placeholder('分组名');
        $form->text()->name('desc')->label('描述')->placeholder('描述');

        $status   = [];
        $status[] = ['val' => 1, 'title' => 'string'];
        $status[] = ['val' => 2, 'title' => 'int'];
        $status[] = ['val' => 3, 'title' => 'json'];
        $status[] = ['val' => 4, 'title' => 'bool'];
        $status[] = ['val' => 5, 'title' => 'float'];
        $status[] = ['val' => 6, 'title' => 'array'];
        $form->select()->name('data_type')->label('更新类型')->options($status);

        return $form;
    }

    //一键同步配置
    public function sync(Request $request)
    {
        $partitionId=$request->param('partition_id',0);
        //获取通用配置信息
        $commonConfigs=BaseSqlConfig::configs;
        $configLists=[];
        foreach ($commonConfigs as $commonConfig) {
            $configLists[]=[
                'name'      =>$commonConfig[0]??'',
                'group'     =>$commonConfig[1]??'',
                'value'     =>$commonConfig[2]??'',
                'desc'      =>$commonConfig[3]??'',
                'data_type' =>$commonConfig[4]??'',
                'status'    =>$commonConfig[5]??1
            ];
        }
        //获取配置信息
        $configs=(new Model)->where('status',1)->field(['name','group','value','desc','data_type','status'])->select()->toArray();
        $configValues=array_column($configs,'value','name');
        $forceConfigFields=array_column($configs,'name');
        //进行数组合并
        $allConfigs=array_merge($configs,$configLists);
        //获取全部签名包信息
        $partitions=\app\common\model\common\PartitionPackage::getPartitionPackageList($partitionId);
        //不同步位置数
        $errorNum=0;
        $forceConfigFields[]='app_domain';
        $forceConfigFields[]='pc_url';
        $forceConfigFields[]='app_abroad_domain';
        $forceConfigFields[]='partition_id';
        $forceConfigFields[]='SendFailMsgKey';
        $forceConfigFields[]='distribution_register_url';
        $forceConfigFields[]='distribution_pay_url';
        $forceConfigFields[]='partition_name';
        $forceConfigFields[]='h5WxLoginAuthUrl';
        $forceConfigFields[]='qqShareUrl';
        $forceConfigFields[]='kwaiurlShareUrl';
        $forceConfigFields[]='douyinShareUrl';
        $forceConfigFields[]='h5ShareUrl';
        $forceConfigFields[]='h5AuthUrl';
        foreach ($partitions as $sign){
            $db=getSwitchDatabaseModel(
                $sign['partition_id'],
                $sign['api_mysql_host_name'],
                $sign['api_mysql_database'],
                $sign['api_mysql_username'],
                $sign['api_mysql_password'],
                $sign['api_mysql_hostport']
            );
            $h5Url=$sign['h5_url']?rtrim($sign['h5_url'],'/'):'';
            foreach ($allConfigs as $config){
                if ($config['name']=='app_domain'){
                    $config['value']=$sign['api_url']?rtrim($sign['api_url'],'/').'/':'';
                }elseif ($config['name']=='pc_url'){
                    $config['value']=$sign['pc_url']?rtrim($sign['pc_url'],'/').'/':'';
                }elseif ($config['name']=='app_abroad_domain'){
                    $config['value']=$sign['abroad_api_url']?rtrim($sign['abroad_api_url'],'/').'/':'';
                }elseif ($config['name']=='partition_id'){
                    $config['value']=$sign['partition_id'];
                }elseif ($config['name']=='SendFailMsgKey'){
                    $config['value']=$sign['send_key']?rtrim($sign['send_key']):'';
                }elseif ($config['name']=='distribution_register_url'){
                    $commonH5Url=$configValues['CommonH5Domain']??'';
                    $config['value']=$commonH5Url?sprintf('%s/register/?partition_id=%s',rtrim($commonH5Url,'/'),$sign['partition_id']):'';
                }elseif ($config['name']=='distribution_pay_url'){
                    $commonH5Url=$configValues['CommonH5Domain']??'';
                    $config['value']=$commonH5Url?sprintf('%s/?partition_id=%s',rtrim($commonH5Url,'/'),$sign['partition_id']):'';
                }elseif ($config['name']=='h5WxLoginAuthUrl'){
                    $config['value']=sprintf('%s',$h5Url);
                }elseif ($config['name']=='qqShareUrl'){
                    $config['value']=sprintf('%s/webView?h5Sign=%s&rankCode=',$h5Url,generateRandomString(5));
                }elseif ($config['name']=='h5AuthUrl'){
                    $config['value']=sprintf('%s',$h5Url);
                }elseif ($config['name']=='kwaiurlShareUrl'){
                    $config['value']=sprintf('%s/webView?h5Sign=%s&rankCode=',$h5Url,generateRandomString(5));
                }elseif ($config['name']=='douyinShareUrl'){
                    $config['value']=sprintf('%s/webView?h5Sign=%s&rankCode=',$h5Url,generateRandomString(5));
                }elseif ($config['name']=='h5ShareUrl'){
                    $config['value']=sprintf('%s/login?h5Sign=%s&rankCode=',$h5Url,generateRandomString(5));
                }elseif ($config['name']=='h5AbroadShareUrl'){
                    $config['value']=sprintf('%s/login?h5Sign=%s&rankCode=',$h5Url,generateRandomString(5));
                }elseif ($config['name']=='partition_name'){
                    $config['value']=sprintf('%s',$sign['partition_name']);
                }

                $data=$db->table('config')->where('status',1)->where('name',$config['name'])->field(['id','value','name'])->findOrEmpty();
                if (!empty($data['id'])){
                    $ret=true;
                    if ((empty($data['value']) && $config['value']) || (in_array($data['name'],$forceConfigFields))){
                        $config['update_time']=time();
                        $ret=$db->table('config')->where('id',$data['id'])->update($config);
                    }
                }else{
                    $config['create_time']=time();
                    $ret=$db->table('config')->insert($config);
                }
                if (!$ret){
                    $errorNum++;
                }
            }
        }
        if ($errorNum>0){
            return json(['code' => -1, 'msg' => '同步失败，共'.$errorNum.'处', 'data' => '']);
        }
        return json(['code' => 0, 'msg' => '同步成功', 'data' => '']);
    }
}